package com.rimi.project.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rimi.project.bean.User;
import com.rimi.project.dao.UserDao;
import com.rimi.project.dao.impl.UserDaoImpl;
import com.rimi.project.service.UserService;
import com.rimi.project.service.impl.UserServiceImpl;
import com.rimi.project.util.DESUtil;


@WebServlet("/user/login")
public class LoginServlet extends HttpServlet{
	
	UserService userService = new UserServiceImpl();
	UserDao userDao = new UserDaoImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
	    //获取用户的cookie
//		Cookie[] cookies = req.getCookies();
//		String userName = "";
//		String password = "";
//	
//		for (Cookie cookie : cookies) {
//			String name = cookie.getName();
//			String value = cookie.getValue();
//			// 判断左边的name是不是username
//			if ("username".equals(name)) {
//				userName = value;
//			}
//			if ("password".equals(name)) {
//				password = value;
//			}
//		}
	 
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		String isRemember = req.getParameter("remember");
			
		User user = userDao.findUserByAccAndPassword(userName, password);
		if (user != null) {
			// 判断是否需要记住密码
			if ("true".equals(isRemember)) {
				// 记住密码
				// 利用Cookie将用户信息写入用户浏览器
				// 写cookie的过程
//				Cookie cookie = new Cookie("username", userName);
//
//				cookie.setMaxAge(120);
//				// 设置cookie当前服务器内可用
//				cookie.setPath("/");
//				// 将Cookie放入响应
//				resp.addCookie(cookie);
//
//				cookie = new Cookie("password", password);
//
//				cookie.setMaxAge(120);
//
//				resp.addCookie(cookie);
				
				// 可以制作一个token令牌，一般包含userName、password、当前时间等敏感					
				String token = getToken(userName,password);

				Cookie cookie = new Cookie("token", token);
				
				cookie.setMaxAge(120);
				
				cookie.setPath(req.getContextPath());
				
				resp.addCookie(cookie);
			} 
			
			// 获取session对象
			HttpSession session = req.getSession();
			// 将username放入session对象
			session.setAttribute("username", userName);
			// 通过请求转发，跳转到主页，跳转地址
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} else {
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
	}
	
	private String getToken(String userName,String password) {
		StringBuffer stringBuffer = new StringBuffer();
		
		stringBuffer.append(userName)
					.append(",")
					.append(password)
					.append(",")
					.append(System.currentTimeMillis());
		
		// 将构造的字符串整体加密
		return DESUtil.encode(stringBuffer.toString());
	}
}
